import {
    // makeObservable,
    makeAutoObservable,
    // observable,
    // action,
    // computed,
    // autorun,
    // reaction,
    // configure,
    runInAction
} from 'mobx'
import { message } from 'antd'
import { myFectch } from '../../utils/useFetch'

// configure({
//     enforceActions:'nevers'
// })
class Goods {
    constructor() {
        /* makeObservable(this,{
            count:observable,
            increment:action.bound,
            reset:action.bound,
            decrement:action.bound,
            double:computed
        }) */
        //1.target 让哪个对象变成可观察
        //2.排除属性和方法
        //3.指定自动绑定this
        makeAutoObservable(this, {}, { autoBind: true })
    }
    goodsType = ['全部', '飞机', '汽车', '乐器', '益智', '娃娃']//类目
    goods = [
        {
            id: 1,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '大飞机',
            goodsType: '飞机',
            price: 99,
            status: '下架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        }, {
            id: 2,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '奥迪',
            goodsType: '汽车',
            price: 99,
            status: '上架',
            goodsWeight: 101,
            goodsIntd: '商品描述',
            postage: "101"
        }, {
            id: 3,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '钢琴',
            goodsType: '乐器',
            price: 99,
            status: '上架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        }, {
            id: 4,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '唐诗三百首',
            goodsType: '益智',
            price: 99,
            status: '上架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        }, {
            id: 5,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '芭比娃娃',
            goodsType: '娃娃',
            price: 99,
            status: '上架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        },
    ]
    oldGoods = [
        {
            id: 1,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '大飞机',
            goodsType: '飞机',
            price: 99,
            status: '下架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        }, {
            id: 2,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '奥迪',
            goodsType: '汽车',
            price: 99,
            status: '上架',
            goodsWeight: 101,
            goodsIntd: '商品描述',
            postage: "101"
        }, {
            id: 3,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '钢琴',
            goodsType: '乐器',
            price: 99,
            status: '上架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        }, {
            id: 4,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '唐诗三百首',
            goodsType: '益智',
            price: 99,
            status: '上架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        }, {
            id: 5,
            imgSrc: 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName: '芭比娃娃',
            goodsType: '娃娃',
            price: 99,
            status: '上架',
            goodsWeight: 100,
            goodsIntd: '商品描述',
            postage: "100"
        },
    ]
    dealResult(target, relations) {//处理回复的数据的键
        const result = [];
        for (let k of target) {
            const every = {};
            for (let i in k) {
                every[relations[i]] = k[i];
            }
            result.push(every)
        }
        return result;
    }
    get integralGoods() {//积分商品
        return this.goods.map((i) => {
            return { id: i.id, key: i.id, goodsName: i.goodsName, goodsType: i.goodsType }
        })
    }
    async selectType(type) {//根据类型选择数据
        const newGoods = this.oldGoods.filter(i => {
            return i.goodsType === type
        })
        this.goods = type === '全部' ? this.oldGoods : newGoods
        // console.log(type);
       /*  if (type === '全部') this.getGoodsData()
        else {
            try {
                const res = await myFectch({
                    url: '/admin1/goodsModel/selectGoodsByCategory',
                    data: {
                        category: type
                    },
                    method: 'post',
                    headers: 'application/x-www-form-urlencoded'
                })
                // console.log(res);
                const result = this.changeResKey(res)
                // console.log(result);//[{}]
                runInAction(() => {
                    this.goods = result
                    // console.log(this.goods);
                })
            } catch (err) {
                console.log('err', err);
            }
        } */
    }
    selectStatus(status) {//根据状态选择数据
        const newGoods = this.oldGoods.filter(i => {
            return i.status === status
        })
        this.goods = status === '全部' ? this.oldGoods : newGoods
    }
    searchGoods(val) {//搜索商品
        const newGoods = this.oldGoods.filter(i => {
            if (i.goodsName.indexOf(val) !== -1) return true
            else return false
        })
        // console.log(newGoods);
        if (newGoods.length > 0) this.goods = newGoods
        return newGoods.length
    }
    //商品管理data
    get tableData() {//按权重排序的表格数据
        const res = this.goods.map(i => {
            i.key = i.id
            return i
        })
        res.sort((a, b) => b.goodsWeight - a.goodsWeight)
        return res
    }
    addGoods(obj, src) {//添加商品
        // const newObj = { ...obj, id: +new Date(), imgSrc: src ? src : 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png' }
        // const newGoods = [newObj, ...this.oldGoods]
        // this.goods = newGoods
        // this.oldGoods = newGoods
        // console.log(obj, src);
        /* goodsIntd: "介绍"
        goodsName: "名称"
        goodsType: "汽车"
        goodsWeight: 999
        imgSrc: "C:\\fakepath\\29812447_p0.jpg"
        postage: 0
        price: "价格"
        status: "上架" */
        let { goodsIntd, goodsName, goodsType, goodsWeight, postage, price, status } = obj
        status = status === '上架' ? 1 : 0
        const imgSrc = ['442469781.jpg', '1767878302.jpg'][Math.floor(Math.random() * 2)]
        // console.log(imgSrc);
        const data = {
            categoryName: goodsType,
            content: goodsIntd,
            goodsName: goodsName,
            // "id": 0,
            integral: postage,
            price: price,
            state: status,
            weight: goodsWeight,
            photoName: imgSrc,
        }
        // console.log(data);
        // const formData = new FormData()
        // for(const i in data){
        //     formData.append(i,data[i])
        // }
        /* fetch('http://42.192.83.237:8080/admin/goods/saveOrUpdateGoods',{
            method:'post',
            headers:{ 
                // "content-type": "application/x-www-form-urlencoded",
                'Content-Type': 'application/json'
            },
            body:JSON.stringify(data)
        }) */
        myFectch({
            method: 'post',
            url: '/portal/goods/saveOrUpdateGoods',
            data,
            // headers: "multipart/form-data"
        }).then(res => {
            // console.log(res);
            this.getGoodsData()
            if (res.code === 200) message.success('数据添加成功!')
        }).catch(err => {
            console.log(err);
            // message.error('数据添加失败!')
        })
    }
    async updateGoods(obj, id) {//更新商品的数据
        // console.log(obj, id);
        if (id === undefined) {
            return this.goods = this.oldGoods = this.goods.map(i => {
                if (i.id === obj.id) {
                    i.status = i.status === '上架' ? '下架' : '上架'
                }
                return i
            })
        }
        const res = this.goods.filter(i => i.id !== id)
        this.oldGoods = this.goods = [obj, ...res]
        // obj.status = obj.status === '上架' ? 1 : 0
        // console.log(obj,id);
        /* try {
            const { goodsIntd, goodsName, goodsType, goodsWeight, postage, price, status ,imgSrc} = obj
            const data = {
                categoryName: goodsType,
                content: goodsIntd,
                goodsName,
                id,
                integral: postage,
                price,
                state: status,
                weight: goodsWeight===999?null:goodsWeight,
                photoName:imgSrc.slice(imgSrc.indexOf('com')+3),
            }
            // console.log(data);
            const res = await myFectch({
                method: 'post',
                url: 'http://172.16.123.103:8080/portal/goods/saveOrUpdateGoods',
                data
            })
            console.log('updateGoods-res', res);
            this.getGoodsData()
            message.success(res.msg ? res.msg : '更新数据成功!')
        } catch (err) {
            console.log('updateGoods-err', err);
            message.error('发生错误！' + err.message)
        } */

    }
    selectGoods = []
    setSleGoods(val) {//勾选商品时进入到选择商品数组
        this.selectGoods = val
    }
    changeGoodsStatue(target, status) {//批量改变商品状态
        target.forEach(element => {
            this.goods = this.oldGoods = this.goods.map(i => {
                if (i.id === element.id) {
                    i.status = status
                }
                return i
            })
        });
    }
    async deleteGoods(target) {//批量删除商品
        /* target.forEach(el => {
            this.goods = this.oldGoods = this.goods.filter(i => {
                return i.id !== el.id
            })
        }) */
        // console.log(target);
        const arr = []
        target.forEach(i => {
            arr.push(i.id)
        })
        // console.log(arr);
        try {
            const res = await myFectch({
                url: '/portal/goods/deleteBatch',
                method: 'post',
                data: { ids: arr },
                headers: "application/x-www-form-urlencoded"
            })
            // console.log(arr)
            // console.log('res', res);
            if (res.code !== 200) return message.error('删除失败！')
            this.getGoodsData()
            message.success('删除成功！')
        } catch (err) {
            console.log('err', err);
            message.error('发生错误！' + err.message)
        }
        /* myFectch({
            url:'http://42.192.83.237:8080/admin/goods/deleteBatch',
            data:{ids:arr}
        }).then(res => {
            console.log('res',res);
            this.getGoodsData()
            return '成功'
        }).catch((err)=>{
            console.log('err',err);
            return err.message
        }) */
    }
    async getGoodsData() {//获取全部表格数据
        /* fetch('http://42.192.83.237:8080/admin/goods/showGoods').then(res => {
            // console.log(res);
            return res.ok ? res.json() : Promise.reject({
                status: res.status,
                message: res.statusText
            })
        }) */
        myFectch({
            url: '/portal/goods/showGoodsList',
        }).then(res => {
            //#region 
            /* id:5,
            imgSrc:'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png',
            goodsName:'芭比娃娃',
            goodsType:'娃娃',
            price:99,
            status:'上架',
            goodsWeight:100,
            goodsIntd:'商品描述',
            postage: "100"
            ===>>data:
            categoryName: "飞机"
            goodsName: "飞机书3"
            goodsNumber: "2138808305.jpg"
            id: 19
            integral: 0
            photoPath: "/goods/2138808305.jpg"
            price: 100
            state: 1
            weight: 1 */
            //#endregion
            // console.log(res);
            // if (res.code === 200 || res.msg === '查询成功') {
                // console.log(res);
                const relations = {
                    id: 'id', photoPath: 'imgSrc', goodsName: 'goodsName', categoryName: 'goodsType',
                    price: 'price', state: 'status', weight: 'goodsWeight', goodsNumber: 'goodsNumber', integral: 'postage', content: 'goodsIntd'
                }
                const result = this.dealResult(res, relations)
                // result.imgSrc = 'https://edu303-1312357052.cos.ap-chengdu.myqcloud.com/' +
                result.forEach((i) => {
                    i.imgSrc = 'https://edu303-1312357052.cos.ap-chengdu.myqcloud.com' + i.imgSrc
                    // i.imgSrc = 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png'
                    i.status = i.status === 1 ? '上架' : '下架'
                    i.goodsIntd = i.goodsIntd ? i.goodsIntd : '这是默认商品介绍'
                    i.goodsWeight = i.goodsWeight ? i.goodsWeight : 999
                })
                // console.log(result);
                runInAction(() => {
                    this.oldGoods = this.goods = result
                    this.switch = false
                })
            // } else {
                // console.log(res);
                // message.error('数据请求失败：' + res.code + res.msg)
            // }

        }).catch(err => {
            console.log(err);
            // message.error('数据请求失败：' + err.message)
        })
        try {
            const res = await myFectch({
                url: '/portal/goodsCategory/showAll'
            })
            // console.log(res);
            runInAction(() => {
                this.goodsType = ['全部', ...new Set(res.data.map(v => v.categoryName))]
            })
        } catch (err) {
            console.log(err);
        }
    }
    changeResKey(data) {//改变key的值
        const relations = {
            id: 'id', photoPath: 'imgSrc', goodsName: 'goodsName', categoryName: 'goodsType',
            price: 'price', state: 'status', weight: 'goodsWeight', goodsNumber: 'goodsNumber', integral: 'postage', content: 'goodsIntd'
        }
        const result = this.dealResult(data, relations)
        result.forEach((i) => {
            if (!i.imgSrc.includes('http')) { i.imgSrc = 'https://edu303-1312357052.cos.ap-chengdu.myqcloud.com' + i.imgSrc }
            // i.imgSrc = 'https://cdn3.axureshop.com/demo/2027306/images/%E5%86%85%E5%AE%B9%E7%AE%A1%E7%90%86/u14649.png'
            i.status = i.status === 1 ? '上架' : '下架'
            i.goodsIntd = i.goodsIntd ? i.goodsIntd : '这是默认商品介绍'
        })
        return result
    }
    switch = true
}
const goods = new Goods()
//#region 
// autorun(()=>{//相当于监听
//     console.log(count.count);
// })
// reaction(
//     ()=>count.count,
//     (val,oldval)=>{console.log('count变了',val,oldval);}
// )
//#endregion
export default goods